//
//  RZVoiceRecorder.m
//  RZIM
//
//  Created by reyzhang on 2021/8/18.
//

#import "RZVoiceRecorder.h"
#import <AVFoundation/AVFoundation.h>


static RZVoiceRecorder *rcVoiceRecorderHandler = nil;

@interface RZVoiceRecorder () <AVAudioRecorderDelegate>

//录音设置
@property (nonatomic, strong) NSDictionary *recordSettings;

@property (nonatomic, strong) NSURL *recordTempFileURL;
@property (nonatomic) BOOL isRecording;
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, weak) id<RZVoiceRecorderDelegate> voiceRecorderDelegate;

@end

@implementation RZVoiceRecorder

#pragma mark - Public Methods
+ (RZVoiceRecorder *)defaultVoiceRecorder {
    @synchronized(self) {
        if (nil == rcVoiceRecorderHandler) {
            rcVoiceRecorderHandler = [[[self class] alloc] init];
            
            //录音设置
            NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
            //录音格式
            [recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
            //采样率
            [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
            //通道数
            [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
            //线性采样位数
            [recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
            //音频质量,采样质量
            [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

            rcVoiceRecorderHandler.recordSettings =  recordSettings;


            rcVoiceRecorderHandler.recordTempFileURL =
                [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"tempAC.caf"]];
            NSLog(@"Using File called: %@", rcVoiceRecorderHandler.recordTempFileURL);
        }
        return rcVoiceRecorderHandler;
    }
}



/**
 开始录制
 */
- (BOOL)startRecordWithObserver:(id<RZVoiceRecorderDelegate>)observer {
    self.voiceRecorderDelegate = observer;

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil]; //设置为录制状态
    [audioSession setActive:YES error:nil];

    NSError *error = nil;

    if (nil == self.recorder) {
        self.recorder =
            [[AVAudioRecorder alloc] initWithURL:self.recordTempFileURL settings:self.recordSettings error:&error];
        self.recorder.delegate = self;
        self.recorder.meteringEnabled = YES; //显示声音level
    }

    BOOL isRecord = NO;
    isRecord = [self.recorder prepareToRecord];
    NSLog(@" prepareToRecord is %@", isRecord ? @"success" : @"failed");

    isRecord = [self.recorder record];
    NSLog(@"record is %@", isRecord ? @"success" : @"failed");
    self.isRecording = self.recorder.isRecording;
    return isRecord;
}


/**
 取消录制
 */
- (BOOL)cancelRecord {
    self.voiceRecorderDelegate = nil;
    if (nil != self.recorder && [self.recorder isRecording] &&
        [[NSFileManager defaultManager] fileExistsAtPath:self.recorder.url.path]) {
        [self.recorder stop];
        [self.recorder deleteRecording];
        self.recorder = nil;
        self.isRecording = self.recorder.isRecording;
        
        //通知其他App
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive:NO
                                       withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                                             error:nil];
        
        return YES;
    }
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:NO
                                   withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                                         error:nil];
    
    
    return NO;
}



/**
 停止录制
 */
- (void)stopRecord:(void (^)(NSData *, NSURL *,NSTimeInterval))compeletion {
    if (!self.recorder.url)
        return;
    NSURL *url = [[NSURL alloc] initWithString:self.recorder.url.absoluteString];
    NSTimeInterval audioLength = self.recorder.currentTime;
    [self.recorder stop];
    NSData *currentRecordData = [NSData dataWithContentsOfURL:url];
    self.isRecording = self.recorder.isRecording;
    NSString *path = self.recorder.url.path;
    
    self.recorder = nil;
    
    //结束录制 通知其他App
    [[AVAudioSession sharedInstance] setActive:NO
                                   withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
                                         error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    
    //存储文件
    [currentRecordData writeToFile:path atomically:YES];
    
    compeletion(currentRecordData, url, audioLength);
}
- (CGFloat)updateMeters {
    if (nil != self.recorder) {
        [self.recorder updateMeters];
    }

    float peakPower = [self.recorder averagePowerForChannel:0];
    CGFloat power = (1.0 / 160.0) * (peakPower + 160.0);
    return power;
}
#pragma mark - AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    if ([self.voiceRecorderDelegate respondsToSelector:@selector(RZVoiceAudioRecorderDidFinishRecording:)]) {
        [self.voiceRecorderDelegate RZVoiceAudioRecorderDidFinishRecording:flag];
    }
    self.voiceRecorderDelegate = nil;
    self.isRecording = self.recorder.isRecording;
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    if ([self.voiceRecorderDelegate respondsToSelector:@selector(RZVoiceAudioRecorderDidFinishRecording:)]) {
        [self.voiceRecorderDelegate RZVoiceAudioRecorderDidFinishRecording:error];
    }

    self.voiceRecorderDelegate = nil;
    self.isRecording = self.recorder.isRecording;
}



@end
